package newtank.view.operate;


import newtank.data.MoveOperatorSignal;
import newtank.data.SyncDataSignal;
import newtank.data.assistant.SyncData;
import newtank.utils.OperatorUtils;
import newtank.view.PaintView;
import newtank.view.context.TankViewContext;
import tool.GlobalUniqueGenerator;

import java.awt.event.KeyEvent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author lijiahao
 * @since 2022/3/8
 */
public class TankMoveHandler extends AbstractOperatorHandler {

    /**
     * 是否移动的标记
     */
    private Boolean isMoveFlag = false;
    private final BlockingQueue<String> moveQueue = new ArrayBlockingQueue<>(10);
    private final Object signal = new Object();

    private void putTask(String task) {
        moveQueue.offer(task);
    }

    @Override
    public void run() {

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (KeyEvent.VK_UP == code) {
            putMoveOperator(1);
        } else if (KeyEvent.VK_DOWN == code) {
            putMoveOperator(2);
        } else if (KeyEvent.VK_LEFT == code) {
            putMoveOperator(3);
        } else if (KeyEvent.VK_RIGHT == code) {
            putMoveOperator(4);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();
        if (KeyEvent.VK_UP == code || KeyEvent.VK_DOWN == code || KeyEvent.VK_LEFT == code || KeyEvent.VK_RIGHT == code) {
            putMoveOperator(0);
        }
    }

    private void putMoveOperator(int operatorType) {
        TankViewContext tankViewContext = tankClientFrame.getSelfTankContext();
        String tankId = tankViewContext.getTankId();
        PaintView paintView = tankDrawingCloth.getView(tankId);
        OperatorUtils.operatorView(paintView, operatorType);
        if(tankClientFrame != null) {
            if(operatorType == 0) {
                SyncData syncData = new SyncData();
                syncData.setVersion(tankViewContext.getVersion() + 1);
                syncData.setPosition(tankViewContext.getPosition());
                syncData.setDirection(tankViewContext.getDirection());
                tankClientFrame.sendMessage(new SyncDataSignal(tankId, syncData));
            } else {
                tankClientFrame.sendMessage(new MoveOperatorSignal(tankId,
                        operatorType + "",
                        tankClientFrame.getDynamicSelfUnique() + "_handle_" + GlobalUniqueGenerator.getGlobalId()));
            }
        }
    }
}
